package wqh.controller.json;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import wqh.domain.GeoBuilding;
import wqh.pojo.GeoBuildingTree;
import wqh.pojo.MapRet;
import wqh.service.GeoBuildingService;
import wqh.service.SystemLogService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by devts on 2016/9/25.
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping(value = "/xkGeoLocation")
public class GeoBuildingJSON {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private GeoBuildingService geoBuildingService;

    @Resource
    private SystemLogService systemLogService;

    @ResponseBody
    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    public Object getAll()
    {
//        xkLog.addLog(systemLogService,"查看所有地理位置信息。",xkLog.getMapConfigure());
        List<GeoBuilding> geoBuildingList = geoBuildingService.findAllRecord();
        return MapRet.DATA(geoBuildingList);
    }

    @ResponseBody
    @RequestMapping(value = "/getTree", method = RequestMethod.GET)
    public Object getTree()
    {
//        xkLog.addLog(systemLogService,"所有的地理位置树状图信息。",xkLog.getMapConfigure());
        List<GeoBuilding> geoBuildingList = geoBuildingService.findAllRecord();
        List<GeoBuildingTree> treeList = new ArrayList<GeoBuildingTree>();
        for(int i = 0; i < geoBuildingList.size(); i++)
        {
            int level = geoBuildingList.get(i).getLevel().intValue();
            if(level == 1)
            {
                int level_1_ID = geoBuildingList.get(i).getId();
                GeoBuildingTree tree = new GeoBuildingTree(geoBuildingList.get(i).getId(),
                        geoBuildingList.get(i).getName(),
                        geoBuildingList.get(i).getParent_id(),
                        geoBuildingList.get(i).getLevel(),
                        geoBuildingList.get(i).getPos_x(),
                        geoBuildingList.get(i).getPos_y(),
                        geoBuildingList.get(i).getPicture(),
                        geoBuildingList.get(i).getDescription());
                List<GeoBuildingTree> level2 = new ArrayList<GeoBuildingTree>();
                for(int j = 0; j < geoBuildingList.size(); j++)
                {
                    int parentID;
                    if(geoBuildingList.get(j).getParent_id() == 0 || geoBuildingList.get(j).getName() == null || geoBuildingList.get(j).getLevel().intValue() == 0)
                    {
                        continue;
                    }
                    else
                    {
                        parentID = geoBuildingList.get(j).getParent_id();
                    }
                    if(level_1_ID == parentID)
                    {
                        int level_2_ID = geoBuildingList.get(j).getId();
                        GeoBuildingTree treeLevel2Child = new GeoBuildingTree(geoBuildingList.get(j).getId(),
                                geoBuildingList.get(j).getName(),
                                geoBuildingList.get(j).getParent_id(),
                                geoBuildingList.get(j).getLevel(),
                                geoBuildingList.get(j).getPos_x(),
                                geoBuildingList.get(j).getPos_y(),
                                geoBuildingList.get(j).getPicture(),
                                geoBuildingList.get(j).getDescription());
                        List<GeoBuildingTree> level3 = new ArrayList<GeoBuildingTree>();
                        for(int k = 0; k < geoBuildingList.size(); k++)
                        {
                            int parentID3;
                            if(geoBuildingList.get(k).getParent_id() == 0 || geoBuildingList.get(k).getName() == null || geoBuildingList.get(k).getLevel().intValue() == 0)
                            {
                                continue;
                            }
                            else
                            {
                                parentID3 = geoBuildingList.get(k).getParent_id();
                            }
                            if(level_2_ID == parentID3)
                            {
                                GeoBuildingTree treeLevel3Child = new GeoBuildingTree(geoBuildingList.get(k).getId(),
                                        geoBuildingList.get(k).getName(),
                                        geoBuildingList.get(k).getParent_id(),
                                        geoBuildingList.get(k).getLevel(),
                                        geoBuildingList.get(k).getPos_x(),
                                        geoBuildingList.get(k).getPos_y(),
                                        geoBuildingList.get(k).getPicture(),
                                        geoBuildingList.get(k).getDescription());
                                level3.add(treeLevel3Child);
                            }
                        }
                        treeLevel2Child.setChildren(level3);
                        level2.add(treeLevel2Child);
                    }
                }
                tree.setChildren(level2);
                treeList.add(tree);
            }
        }
        return MapRet.DATA(treeList);
    }


    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object add(@RequestParam(value = "name",required = true) String name,
                      @RequestParam(value = "parent_id",required = false,defaultValue = "1") int parent_id,
                      @RequestParam(value = "level",required = false,defaultValue = "1") int level,
                      @RequestParam(value = "pos_x",required = false,defaultValue = "0") String pos_x,
                      @RequestParam(value = "pos_y",required = false,defaultValue = "0") String pos_y,
                      @RequestParam(value = "picture",required = false,defaultValue = "0") String picture,
                      @RequestParam(value = "description",required = false,defaultValue = "none") String description)
    {
        System.out.println(name);
        System.out.println(parent_id);
        System.out.println(level);
        if(level > 3 || level < 0)
        {
            return MapRet.VALUE_ERROR("level");
        }
        String levelName = null;
        if(level == 1) levelName = "区域: ";
        if(level == 2) levelName = "建筑物: ";
        if(level == 3) levelName = "楼层: ";
        try {
            GeoBuilding geoBuilding = new GeoBuilding();
            geoBuilding.setName(name);
            geoBuilding.setParent_id(parent_id);
            geoBuilding.setLevel((byte)level);
            geoBuilding.setPos_x(pos_x);
            geoBuilding.setPos_y(pos_y);
            geoBuilding.setPicture(picture);
            geoBuilding.setDescription(description);
            if(geoBuildingService.findAllByNameAndParentIDAndLevel(name,parent_id,(byte)level).size() != 0)
            {
                return MapRet.EXIST();
            }
            if(geoBuildingService.insertRecord(geoBuilding) == 0)
            {
                return MapRet.SQL_INSERT_ERROR();
            }

        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("添加地理位置信息错误：" + e.toString());
            return MapRet.SQL_ERROR();
        }


        return MapRet.SQL_SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(@RequestParam(value = "id",required = true) int id,
                      @RequestParam(value = "name",required = true) String name,
                      @RequestParam(value = "parent_id",required = false,defaultValue = "1") int parent_id,
                      @RequestParam(value = "level",required = false,defaultValue = "1") int level,
                      @RequestParam(value = "pos_x",required = false,defaultValue = "0") String pos_x,
                      @RequestParam(value = "pos_y",required = false,defaultValue = "0") String pos_y,
                      @RequestParam(value = "picture",required = false,defaultValue = "0") String picture,
                      @RequestParam(value = "description",required = false,defaultValue = "none") String description)
    {
        if(level > 3 || level < 0)
        {
            return MapRet.VALUE_ERROR("level");
        }

        String levelName = null;
        if(level == 1) levelName = "区域: ";
        if(level == 2) levelName = "建筑物: ";
        if(level == 3) levelName = "楼层: ";
        String nameOld = null;
        try {
            GeoBuilding old = geoBuildingService.findRecordById(id);
            nameOld = old.getName();
            GeoBuilding geoBuilding = new GeoBuilding();
            geoBuilding.setId(id);
            geoBuilding.setName(name);
            geoBuilding.setParent_id(parent_id);
            geoBuilding.setLevel((byte)level);
            geoBuilding.setPos_x(pos_x);
            geoBuilding.setPos_y(pos_y);
            if(picture.equals("0"))
            {
                geoBuilding.setPicture(old.getPicture());
            }
            else
            {
                geoBuilding.setPicture(picture);
            }
            geoBuilding.setDescription(description);
            if(geoBuildingService.updateRecord(geoBuilding) == 0)
            {
                return MapRet.SQL_INSERT_ERROR();
            }

        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("修改指定ID地理位置信息：" + e.toString());
            return MapRet.SQL_ERROR();
        }


        return MapRet.SQL_SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Object delete(HttpServletRequest httpServletRequest, @RequestParam(value = "id",required = true) int id)
    {
        try {

            GeoBuilding g = geoBuildingService.findRecordById(id);
            if(g != null)
            {
                String dbPath = g.getPicture();
                String serverPath = httpServletRequest.getServletContext().getRealPath("/") + dbPath;
                File file = new File(serverPath);
                if(file.isFile() && file.exists())
                {
                    file.delete();
                }

                String name = g.getName();
                String levelName = null;
                int level = g.getLevel();
                if(level == 1) levelName = "区域: ";
                if(level == 2) levelName = "建筑物: ";
                if(level == 3) levelName = "楼层: ";
            }

            if(geoBuildingService.deleteRecord(id) == 0)
            {
                return MapRet.SQL_DELETE_ERROR();
            }

        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("删除设备出错 " + e.toString());
            return MapRet.SQL_ERROR();
        }
        return MapRet.SQL_SUCCESS();
    }


}
